<template>
  <view class="note-detail-container">
    <view class="note-header">
      <uni-icons type="arrowleft" size="24" color="#333" @click="goBack"></uni-icons>
      <text class="title">笔记详情</text>
      <!-- 添加更多按钮 -->
      <uni-icons type="more" size="24" color="#333" @click="showActionMenu"></uni-icons>
    </view>
    <!-- 笔记内容区域 -->
    <scroll-view class="note-content" scroll-y="true" @scrolltolower="loadMoreComments">
      <!-- 作者信息 -->
      <view class="author-section">
        <view class="author-info">
          <image class="avatar" :src="note.author.avatar||defaultUrl" mode="aspectFill"></image>
          <view class="author-meta">
            <text class="nickname">{{note.author.nickname}}</text>
            <text class="time">{{formatTime(note.createTime)}}</text>
          </view>
        </view>
        <button class="follow-btn" @click="toggleFollow">
          {{isFollowing ? '已关注' : '+ 关注'}}
        </button>
      </view>

      <!-- 关联书籍信息 -->
      <view class="book-section" @click="goBookDetail">
        <image class="book-cover" :src="note.book.cover" mode="aspectFill"></image>
        <view class="book-info">
          <text class="book-title">{{note.book.title}}</text>
          <text class="book-author">{{note.book.author}}</text>
        </view>
        <uni-icons type="forward" size="16" color="#999"></uni-icons>
      </view>

      <!-- 笔记内容 -->
      <view class="note-section">
        <text class="note-title">{{note.title}}</text>
        <rich-text class="note-body" :nodes="note.content"></rich-text>
        <view class="note-images" v-if="note.images.length > 0">
          <image v-for="(img, index) in note.images" :key="index" :src="img" mode="aspectFill"
            @click="previewImage(index)"></image>
        </view>
        <view class="note-tags">
          <text v-for="(tag, index) in note.tags" :key="index" class="tag">#{{tag}}</text>
        </view>
      </view>

      <!-- 互动区域 -->
      <view class="interaction-section">
        <view class="interaction-item" @click="toggleLike">
          <uni-icons type="heart" size="20" :color="isLiked ? '#FF6B6B' : '#666'" :filled="isLiked"></uni-icons>
          <text class="count">{{note.likeCount}}</text>
        </view>
        <view class="interaction-item" @click="focusCommentInput">
          <uni-icons type="chat" size="20" color="#666"></uni-icons>
          <text class="count">{{note.commentCount}}</text>
        </view>
        <view class="interaction-item" @click="shareNote">
          <uni-icons type="paperplane" size="20" color="#666"></uni-icons>
          <text class="count">{{note.shareCount}}</text>
        </view>
        <view class="interaction-item" @click="toggleCollect">
          <uni-icons type="star" size="20" :color="isCollected ? '#FFC107' : '#666'" :filled="isCollected"></uni-icons>
          <text class="count">{{note.collectCount}}</text>
        </view>
      </view>

      <!-- 评论区 -->
      <view class="comment-section">
        <view class="section-title">
          <text>评论 {{note.commentCount}}</text>
        </view>

        <view class="comment-list">
          <view v-for="comment in comments" :key="comment.id" class="comment-item">
            <image class="avatar" :src="comment.author.avatar" mode="aspectFill"></image>
            <view class="comment-content">
              <view class="comment-header">
                <text class="nickname">{{comment.author.nickname}}</text>
                <text class="time">{{formatTime(comment.createTime)}}</text>
              </view>
              <text class="comment-text">{{comment.content}}</text>
              <view class="comment-actions">
                <view class="action-item" @click="toggleCommentLike(comment)">
                  <uni-icons type="hand-up" size="16" :color="comment.isLiked ? '#2A5CAA' : '#999'"></uni-icons>
                  <text class="action-count">{{comment.likeCount}}</text>
                </view>
                <view class="action-item" @click="replyComment(comment)">
                  <uni-icons type="redo" size="16" color="#999"></uni-icons>
                  <text class="action-text">回复</text>
                </view>
              </view>

              <!-- 回复列表 -->
              <view class="reply-list" v-if="comment.replies.length > 0">
                <view v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <text class="reply-text">
                    <text class="reply-user">{{reply.author.nickname}}</text>
                    回复
                    <text class="reply-user">{{reply.replyTo.nickname}}:</text>
                    {{reply.content}}
                  </text>
                </view>
                <view class="view-more-replies" v-if="comment.replies.length < comment.replyCount"
                  @click="loadMoreReplies(comment)">
                  <text>展开{{comment.replyCount - comment.replies.length}}条回复</text>
                  <uni-icons type="arrowdown" size="14" color="#999"></uni-icons>
                </view>
              </view>
            </view>
          </view>

          <view class="load-more" v-if="hasMoreComments">
            <text>{{loadingComments ? '加载中...' : '上拉加载更多'}}</text>
          </view>

          <view class="empty-comments" v-if="comments.length === 0">
            <image src="/static/images/empty-comments.png" mode="widthFix"></image>
            <text>还没有评论，快来抢沙发~</text>
          </view>
        </view>

      </view>

    </scroll-view>

    <!-- 底部评论输入框 -->
    <view class="comment-input-section">
      <view class="input-container">
        <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <input class="comment-input" v-model="commentText"
          :placeholder="replyTo ? '回复@' + replyTo.nickname : '写下你的评论...'" :focus="isInputFocus" @focus="onInputFocus"
          @blur="onInputBlur" />
        <button class="send-btn" :class="{active: commentText.trim().length > 0}" @click="sendComment">
          发送
        </button>
      </view>
    </view>

    <!-- 操作菜单 -->
    <uni-popup ref="actionMenu" type="bottom">
      <view class="action-menu">
        <view class="menu-item" @click="editNote" v-if="isAuthor">
          <uni-icons type="compose" size="18" color="#666"></uni-icons>
          <text>编辑笔记</text>
        </view>
        <view class="menu-item" @click="deleteNote" v-if="isAuthor">
          <uni-icons type="trash" size="18" color="#666"></uni-icons>
          <text>删除笔记</text>
        </view>
        <view class="menu-item" @click="reportNote" v-if="!isAuthor">
          <uni-icons type="flag" size="18" color="#666"></uni-icons>
          <text>举报笔记</text>
        </view>
        <view class="menu-item" @click="copyLink">
          <uni-icons type="paperclip" size="18" color="#666"></uni-icons>
          <text>复制链接</text>
        </view>
        <view class="menu-item cancel" @click="closeActionMenu">
          <text>取消</text>
        </view>
      </view>
    </uni-popup>

    <!-- 删除确认弹窗 -->
    <uni-popup ref="deleteConfirm" type="dialog">
      <uni-popup-dialog type="warn" title="删除笔记" content="确定要删除这篇笔记吗？删除后不可恢复" :duration="2000" :before-close="true"
        @confirm="confirmDelete" @close="closeDeleteConfirm"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        defaultUrl: '/static/my.jpg',
        note: {
          id: null,
          title: '',
          author: { // 确保author有初始结构
            id: null,
            nickname: '',
            avatar: ''
          },
          book: {
            id: null,
            title: '',
            cover: ''
          }
        },
        userInfo: {},
        comments: [{
            id: 10001,
            content: '分析得很透彻，我也觉得故事特别打动人',
            createTime: '2023-05-16T14:20:00',
            likeCount: 24,
            isLiked: false,
            replyCount: 3,
            author: {
              id: 102,
              nickname: '书迷小王',
              avatar: '/static/my.jpg'
            },
            replies: [{
              id: 100011,
              content: '谢谢你的认同！',
              createTime: '2023-05-16T15:30:00',
              author: {
                id: 101,
                nickname: '文学评论家',
                avatar: '/static/my.jpg'
              },
              replyTo: {
                id: 102,
                nickname: '书迷小王'
              }
            }]
          },
          {
            id: 10002,
            content: '作者对这本书的理解确实很到位',
            createTime: '2023-05-17T09:45:00',
            likeCount: 12,
            isLiked: true,
            replyCount: 0,
            author: {
              id: 103,
              nickname: '阅读达人',
              avatar: '/static/my.jpg'
            },
            replies: []
          }
        ],

        commentText: '',
        replyTo: null,
        isInputFocus: false,
        loadingComments: false,
        hasMoreComments: true,
        page: 1,
        pageSize: 10
      }
    },
    computed: {
      isAuthor() {
        return this.userInfo.id === this.note.author.id
      },
      isFollowing() {
        return this.note.author.isFollowing
      },
      isLiked() {
        return this.note.isLiked
      },
      isCollected() {
        return this.note.isCollected
      }
    },
    methods: {
      async fetchData(id) {
        const {
          data
        } = await uni.$http.get(`/note/${id}`)
        this.note = data.data.note
        this.userInfo = data.data.userInfo
      },
      goBack() {
        uni.navigateBack()
      },
      formatTime(timestamp) {
        const now = new Date()
        const date = new Date(timestamp)
        const diffDays = Math.floor((now - date) / 86400000)

        if (diffDays === 0) {
          const diffHours = Math.floor((now - date) / 3600000)
          if (diffHours === 0) {
            const diffMinutes = Math.floor((now - date) / 60000)
            return `${diffMinutes}分钟前`
          }
          return `${diffHours}小时前`
        } else if (diffDays === 1) {
          return '昨天'
        } else if (diffDays < 7) {
          return `${diffDays}天前`
        } else {
          return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
        }
      },
      toggleFollow() {
        this.note.author.isFollowing = !this.note.author.isFollowing
        uni.showToast({
          title: this.note.author.isFollowing ? '关注成功' : '已取消关注',
          icon: 'none'
        })
      },
      toggleLike() {
        this.note.isLiked = !this.note.isLiked
        this.note.likeCount += this.note.isLiked ? 1 : -1
        // 这里应该调用API更新点赞状态
      },
      toggleCollect() {
        this.note.isCollected = !this.note.isCollected
        uni.showToast({
          title: this.note.isCollected ? '已收藏' : '已取消收藏',
          icon: 'none'
        })
        // 这里应该调用API更新收藏状态
      },
      toggleCommentLike(comment) {
        comment.isLiked = !comment.isLiked
        comment.likeCount += comment.isLiked ? 1 : -1
        // 这里应该调用API更新评论点赞状态
      },
      shareNote() {
        uni.share({
          provider: 'weixin',
          type: 0,
          title: this.note.title,
          summary: `来自${this.note.author.nickname}的读书笔记`,
          success: () => {
            this.note.shareCount++
            uni.showToast({
              title: '分享成功',
              icon: 'success'
            })
          }
        })
      },
      goBookDetail() {
        uni.navigateTo({
          url: `/subpkg/book_info/book_info?id=${this.note.book.id}&title=${encodeURIComponent(this.note.book.title)}`
        })
      },
      previewImage(index) {
        uni.previewImage({
          current: index,
          urls: this.note.images
        })
      },
      showActionMenu() {
        this.$refs.actionMenu.open()
      },
      closeActionMenu() {
        this.$refs.actionMenu.close()
      },
      editNote() {
        const noteData = {
          id: this.note.id,
          title: this.note.title,
          content: this.note.content,
          images: this.note.images,
          tags: this.note.tags,
          bId: this.note.book.id
        }
        uni.navigateTo({
          url: `/subpkg/edit_note/edit_note?note=${encodeURIComponent(JSON.stringify(noteData))}`
        })
        this.closeActionMenu()
      },
      deleteNote() {
        this.$refs.deleteConfirm.open()
        this.closeActionMenu()
      },
      closeDeleteConfirm() {
        this.$refs.deleteConfirm.close()
      },
      confirmDelete() {
        // 这里应该调用API删除笔记
        uni.showToast({
          title: '笔记已删除',
          icon: 'success'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      },
      reportNote() {
        uni.navigateTo({
          url: '/pages/report/report?type=note&id=' + this.note.id
        })
        this.closeActionMenu()
      },
      copyLink() {
        uni.setClipboardData({
          data: `https://example.com/notes/${this.note.id}`,
          success: () => {
            uni.showToast({
              title: '链接已复制',
              icon: 'none'
            })
          }
        })
        this.closeActionMenu()
      },
      focusCommentInput() {
        this.isInputFocus = true
      },
      onInputFocus() {
        // 可以在这里做一些输入框获取焦点时的处理
      },
      onInputBlur() {
        // 可以在这里做一些输入框失去焦点时的处理
      },
      replyComment(comment) {
        this.replyTo = {
          id: comment.author.id,
          nickname: comment.author.nickname,
          commentId: comment.id
        }
        this.focusCommentInput()
      },
      sendComment() {
        if (!this.commentText.trim()) {
          uni.showToast({
            title: '评论内容不能为空',
            icon: 'none'
          })
          return
        }

        const newComment = {
          id: Date.now(),
          content: this.commentText,
          createTime: new Date().toISOString(),
          likeCount: 0,
          isLiked: false,
          replyCount: 0,
          author: {
            ...this.userInfo
          },
          replies: []
        }

        if (this.replyTo) {
          // 如果是回复评论，添加到对应评论的回复列表
          const parentComment = this.comments.find(c => c.id === this.replyTo.commentId)
          if (parentComment) {
            newComment.replyTo = {
              id: this.replyTo.id,
              nickname: this.replyTo.nickname
            }
            parentComment.replies.push(newComment)
            parentComment.replyCount++
          }
        } else {
          // 否则添加为新评论
          this.comments.unshift(newComment)
        }

        this.note.commentCount++
        this.commentText = ''
        this.replyTo = null
        uni.showToast({
          title: '评论成功',
          icon: 'success'
        })

        // 这里应该调用API提交评论
      },
      loadMoreComments() {
        if (this.loadingComments || !this.hasMoreComments) return

        this.loadingComments = true
        // 模拟加载更多评论
        setTimeout(() => {
          const newComments = Array.from({
            length: 5
          }, (_, i) => ({
            id: 20000 + this.page * this.pageSize + i,
            content: `这是第${this.page * this.pageSize + i + 1}条评论`,
            createTime: new Date(Date.now() - 86400000 * (i + 2)).toISOString(),
            likeCount: Math.floor(Math.random() * 10),
            isLiked: false,
            replyCount: 0,
            author: {
              id: 300 + i,
              nickname: ['用户', '读者', '书友', '访客', '会员'][i],
              avatar: `/static/my.jpg`
            },
            replies: []
          }))

          this.comments = [...this.comments, ...newComments]
          this.page++
          this.loadingComments = false
          this.hasMoreComments = this.page < 3 // 模拟最多3页数据
        }, 1000)
      },
      loadMoreReplies(comment) {
        // 模拟加载更多回复
        const newReplies = Array.from({
          length: 2
        }, (_, i) => ({
          id: 30000 + comment.replies.length + i,
          content: `这是第${comment.replies.length + i + 1}条回复`,
          createTime: new Date(Date.now() - 86400000 * (i + 1)).toISOString(),
          author: {
            id: 400 + i,
            nickname: ['回复者', '参与者'][i],
            avatar: `/static/images/avatar${(i % 4) + 1}.jpg`
          },
          replyTo: {
            id: comment.author.id,
            nickname: comment.author.nickname
          }
        }))

        comment.replies = [...comment.replies, ...newReplies]
      }
    },
    onLoad(options) {
      this.fetchData(options.id)
    }

  }
</script>

<style lang="scss">
  .note-detail-container {
    background-color: #f8f9fa;
    min-height: 100vh;
  }

  .note-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
  }

  .note-content {
    height: calc(100vh - 50px);
  }

  .author-section {
    display: flex;
    justify-content: space-between;
    /* 确保元素分布在两端 */
    align-items: center;
    padding: 15px;
    background-color: #fff;
    margin-bottom: 10px;

    .author-info {
      display: flex;
      align-items: center;
      flex: 1;
      /* 让作者信息区域占据剩余空间 */

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: 10px;
      }

      .author-meta {
        display: flex;
        flex-direction: column;

        .nickname {
          font-size: 15px;
          font-weight: bold;
          color: #333;
        }

        .time {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .follow-btn {
      font-size: 12px;
      color: #2A5CAA;
      border: 1px solid #2A5CAA;
      border-radius: 15px;
      background-color: #fff;
      margin-left: auto;
      /* 关键属性：将按钮推到最右侧 */

      &:after {
        border: none;
      }
    }
  }

  .book-section {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    background-color: #fff;
    margin-bottom: 10px;

    .book-cover {
      width: 50px;
      height: 70px;
      border-radius: 4px;
      margin-right: 12px;
    }

    .book-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .book-title {
        font-size: 15px;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
        white-space: nowrap;
        max-width: 250px;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .book-author {
        font-size: 12px;
        color: #666;
      }
    }
  }

  .note-section {
    padding: 15px;
    background-color: #fff;
    margin-bottom: 10px;

    .note-title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-bottom: 15px;
      line-height: 1.4;
    }

    .note-body {
      font-size: 15px;
      color: #333;
      line-height: 1.6;
      margin-bottom: 15px;
    }

    .note-images {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 15px;

      image {
        width: calc(50% - 5px);
        height: 120px;
        border-radius: 4px;
        margin-right: 10px;
        margin-bottom: 10px;

        &:nth-child(2n) {
          margin-right: 0;
        }
      }
    }

    .note-tags {
      display: flex;
      flex-wrap: wrap;

      .tag {
        font-size: 12px;
        color: #2A5CAA;
        background-color: #f0f6ff;
        padding: 4px 8px;
        border-radius: 4px;
        margin-right: 8px;
        margin-bottom: 8px;
      }
    }
  }

  .interaction-section {
    display: flex;
    justify-content: space-around;
    padding: 12px 0;
    background-color: #fff;
    margin-bottom: 10px;

    .interaction-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      /* 添加固定宽度确保间距均匀 */
      width: 25%;

      /* 统一图标容器大小 */
      .uni-icons {
        width: 24px;
        height: 24px;
        display: flex;
        justify-content: center;
        align-items: center;
        /* 强制图标使用相同大小 */
        font-size: 20px !important;
      }

      .count {
        font-size: 12px;
        color: #666;
        margin-top: 4px;
      }
    }
  }

  .comment-section {
    background-color: #fff;
    padding: 15px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 15px;
    }

    .comment-list {
      .comment-item {
        display: flex;
        margin-bottom: 15px;

        .avatar {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          margin-right: 10px;
        }

        .comment-content {
          flex: 1;

          .comment-header {
            display: flex;
            align-items: center;
            margin-bottom: 5px;

            .nickname {
              font-size: 14px;
              font-weight: bold;
              color: #333;
              margin-right: 10px;
            }

            .time {
              font-size: 12px;
              color: #999;
            }
          }

          .comment-text {
            font-size: 14px;
            color: #333;
            line-height: 1.5;
            margin-bottom: 8px;
          }

          .comment-actions {
            display: flex;
            align-items: center;

            .action-item {
              display: flex;
              align-items: center;
              margin-right: 15px;

              .action-count {
                font-size: 12px;
                color: #999;
                margin-left: 3px;
              }

              .action-text {
                font-size: 12px;
                color: #999;
                margin-left: 3px;
              }
            }
          }

          .reply-list {
            margin-top: 10px;
            padding-left: 10px;
            border-left: 2px solid #f0f0f0;

            .reply-item {
              padding: 8px 0;
              border-bottom: 1px solid #f5f5f5;

              .reply-text {
                font-size: 13px;
                color: #666;
                line-height: 1.5;

                .reply-user {
                  color: #2A5CAA;
                }
              }
            }

            .view-more-replies {
              display: flex;
              align-items: center;
              padding: 8px 0;
              font-size: 12px;
              color: #999;

              .uni-icons {
                margin-left: 3px;
              }
            }
          }
        }
      }

      .load-more {
        text-align: center;
        padding: 15px 0;
        font-size: 14px;
        color: #999;
      }

      .empty-comments {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 30px 0;

        image {
          width: 120px;
          height: 120px;
          margin-bottom: 15px;
        }

        text {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }

  .comment-input-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 8px 15px;
    border-top: 1px solid #f0f0f0;

    .input-container {
      display: flex;
      align-items: center;

      .avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 10px;
      }

      .comment-input {
        flex: 1;
        height: 36px;
        padding: 0 12px;
        background-color: #f5f5f5;
        border-radius: 18px;
        font-size: 14px;
      }

      .send-btn {
        margin-left: 10px;
        padding: 0 15px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
        color: #999;
        background-color: #f5f5f5;
        border-radius: 18px;

        &.active {
          color: #fff;
          background-color: #2A5CAA;
        }

        &:after {
          border: none;
        }
      }
    }
  }

  .action-menu {
    background-color: #fff;
    border-radius: 12px 12px 0 0;
    padding: 15px;

    .menu-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      font-size: 15px;
      color: #333;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      &.cancel {
        justify-content: center;
        color: #666;
        margin-top: 10px;
      }

      .uni-icons {
        margin-right: 10px;
      }
    }
  }
</style>
